package be.kuleuven.thesis.neo4j;

import java.io.IOException;

import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;

import be.kuleuven.thesis.neo4j.Neo4jDBManager.RelTypes;
import be.kuleuven.thesis.parsers.MyFeatureI;
import be.kuleuven.thesis.parsers.MyFeatureList;
import be.kuleuven.thesis.parsers.MyGeneIDGFF2Reader;


public class CreadeProteinNodeAndRelations {
	private static Neo4jDBManager dbManager;
	private static GraphDatabaseService myGraphDb;
	private static String geneId;
	private static String proteinId;
	private static Label label;
	private static String propertyIndex;
	private static Relationship relationship;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		dbManager = new Neo4jDBManager();
		myGraphDb = dbManager.getGraphDb();
		
		MyFeatureList features = MyGeneIDGFF2Reader.read("/home/moni/Documents/BioinformaticsMaster/Thesis/DataITM/SNP/ReferenceFiles/LD.ALL.M2.gff");
		
		label = DynamicLabel.label("protein");
		propertyIndex = "protein_id";
		dbManager.createIndexLabelProperty(label, propertyIndex);
		
		try ( Transaction tx = dbManager.getGraphDb().beginTx()) {
			for(MyFeatureI feature : features){
				if(feature.hasAttribute("protein_id")){
					Node proteinNode = createProteinNode(feature);
					geneId = feature.getAttribute("locus_tag");
					Label geneLabel = DynamicLabel.label("gene"); 
					ResourceIterator<Node> genes = dbManager.graphDb.findNodesByLabelAndProperty( geneLabel, "locus_tag", geneId ).iterator();
					
					while(genes.hasNext()){
						relationship = genes.next().createRelationshipTo(proteinNode, RelTypes.ENCODES);
					}
				}
			}
			
			tx.success();
		}	

	}
	
	public static Node createProteinNode(MyFeatureI feature){
		label = DynamicLabel.label("protein");
		propertyIndex = "protein_id";
		//dbManager.createIndexLabelProperty(label, propertyIndex);
		proteinId = feature.getAttribute(propertyIndex);
		
		Node node = myGraphDb.createNode(label);
	    node.setProperty(propertyIndex, proteinId);
	    
	    if(feature.hasAttribute("product"))
	    	node.setProperty("product", feature.getAttribute("product"));
	    if(feature.hasAttribute("db_xref")){
	    	String[] db_xrefs = new String[feature.getAttributeList("db_xref").size()];
        	db_xrefs = feature.getAttributeList("db_xref").toArray(db_xrefs);
        	node.setProperty("db_xref", db_xrefs);
        }
	    return node;
	}

}
